package com.falling.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.falling.reggie.common.R;
import com.falling.reggie.entity.User;
import com.falling.reggie.service.UserService;
import com.falling.reggie.service.impl.MailService;
import com.falling.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private MailService mailService;


    @PostMapping("/sendMail")
    public R<String> sendMail(@RequestBody User user, HttpSession session){
        String mailAds = user.getPhone();

        // 生成验证码
        String code = ValidateCodeUtils.generateValidateCode4String(4);
        log.info("code = {}", code);

        String text = (user.getName() == null ? "新用户" : user.getName()) + "您好，\n您本次登录的验证码为："+code;
        mailService.sendTextMailMessage(mailAds, "瑞吉外卖 验证码", text);

        // 保存验证码，用于检验用户输入的是否正确
        session.setAttribute(mailAds, code);

        return R.success("send mail success...");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String, String> map, HttpSession session){
        String mailAds = map.get("phone");
        String code = map.get("code");

        log.info("code = {}, mailAds = {}", code, mailAds);

        // 获取发出的code
        String codeInSession = session.getAttribute(mailAds).toString();

        // 比对
        if (codeInSession != null && codeInSession.equals(code)){

            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, mailAds);

            User user = userService.getOne(queryWrapper);
            boolean save = false;
            if (user == null){
                user = new User();
                user.setPhone(mailAds);
                user.setStatus(1);

                save = userService.save(user);
            }

            session.setAttribute("user", user.getId());
            return R.success(user);
        }
        return R.error("login fail...");
    }

    @PostMapping("/logout")
    public R<String> logout(HttpSession session){
        session.removeAttribute("user");
        return R.success("exit success...");

    }


}
